/* eslint-disable jsx-a11y/anchor-is-valid */
/* eslint-disable react-hooks/exhaustive-deps */
import React, { useState, useEffect } from 'react';
import { Form, Input, Select, Button, message, Divider } from 'antd';
import Icon from '@/components/SvgIcon';
import { MinusCircleOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { SelectProps } from 'antd';
import {
  analysisConfigListAPI,
  getUnbindDeviceAPI,
  addRuleConfigAPI,
  bindSensorAPI,
  unBindSensorAPI,
} from '@/api/visualiza';
import { useNavigate } from 'react-router-dom';
import classNames from 'classnames';
import style from './analysisConfig.module.scss';
import Table from '@/components/table';
import BeforefixSelect from '@/components/BeforefixSelect';
import { useRequest } from 'ahooks';
import { getDeviceTypeStatistics } from '@/api/deviceStatus';
import DefaultModal from '@/components/modal';
import useModal from '@/hooks/useModal';
import SelectDebounce from '@/components/SelectDebounce';
import Ellipsis from '@/components/ellipsis-text';

const { TextArea } = Input;

type DataType = API.AnalysisConfigResult & {
  index?: number;
};
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 5 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 19 },
  },
};

const formItemLayoutWithOutLabel = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 19, offset: 5 },
  },
};

const AnalysisConfig: React.FC = () => {
  const [modal, contextHolder] = useModal();
  let navigate = useNavigate();
  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 56,
      render: (_, __, index) => {
        return <>{index + 1 + (pagination.page - 1) * pagination.pageSize}</>;
      },
    },
    {
      title: '设备类型',
      dataIndex: 'type',
      key: 'type',
      render: value => <Ellipsis content={value} />,
    },
    {
      title: '设备编号',
      dataIndex: 'deviceCode',
      key: 'deviceCode',
      render: value => <Ellipsis content={value} />,
    },
    {
      title: '传感器编号',
      dataIndex: 'collectionDeviceCode',
      key: 'collectionDeviceCode',
      ellipsis: true,
      render: (collectionDeviceCode, recode) => {
        return recode.children && recode.children.length !== 0 ? (
          recode.children.map(item => item.collectionDeviceCode).join(' / ')
        ) : collectionDeviceCode ? (
          <Ellipsis content={collectionDeviceCode} />
        ) : (
          '-'
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'operate',
      key: 'operate',
      width: 180,
      render: (_, recode) => {
        let disabled = !recode.collectionDeviceCode && !recode.children;
        return (
          <>
            <Button
              type="link"
              style={{ padding: 0, margin: 0, height: 22, color: '#4E6FF5' }}
              onClick={() => {
                let result =
                  recode.children && recode.children.length !== 0
                    ? recode.children.map(item => item.collectionDeviceCode)
                    : recode.collectionDeviceCode
                    ? [recode.collectionDeviceCode]
                    : [];
                setSensor(result as string[]);
                console.log(recode.deviceCode);
                setCurrentDeviceType(recode.deviceCode);
                setIsSensorModalOpen(true);
              }}>
              传感器管理
            </Button>
            {recode?.collectionDeviceCode && (
              <>
                <Divider
                  type="vertical"
                  style={{ height: 14, borderInlineStartColor: '#DCDEE0' }}
                />
                <Button
                  type="link"
                  style={{
                    padding: 0,
                    margin: 0,
                    height: 22,
                    color: '#4E6FF5',
                  }}
                  onClick={() => {
                    navigate(`/systemConfig/ruleConfig/${recode.deviceCode}`);
                  }}
                  disabled={disabled}>
                  配置参数
                </Button>
              </>
            )}
          </>
        );
      },
    },
  ];
  const [dataSource, setDataSource] = useState<API.AnalysisConfigResult[]>([]);
  const [sensor, setSensor] = useState<string[]>([]);
  const [deviceTypeOptions, setDeviceTypeOptions] =
    useState<SelectProps['options']>();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isSensorModalOpen, setIsSensorModalOpen] = useState(false);
  const [currentDeviceType, setCurrentDeviceType] = useState<string>();
  const [btnLoading, setBtnLoading] = useState<boolean>(false);
  const [pagination, setPagination] = useState({
    page: 1,
    pageSize: 10,
    total: 0,
  });

  const [filterForm] = Form.useForm();
  const [addForm] = Form.useForm();
  const [sensorForm] = Form.useForm();

  // 获取采集配置列表
  const { loading: tableLoading, run: getConfigList } = useRequest(
    () =>
      analysisConfigListAPI({
        ...filterForm.getFieldsValue(),
        page: pagination.page,
        pageSize: pagination.pageSize,
      }),
    {
      onSuccess: (res: any) => {
        setDataSource(res?.data?.records);
        setPagination({
          page: res?.data?.page,
          pageSize: res?.data?.pageSize,
          total: res?.data?.total,
        });
      },
      onError: err => {
        console.log(err);
      },
    }
  );

  useEffect(() => {
    // get 设备类型
    getDeviceTypeStatistics({}).then(res => {
      let types = res?.data.map((item: any) => {
        return {
          label: `${item.deviceType}(${item.devCount})`,
          value: item.deviceType,
        };
      });
      setDeviceTypeOptions(types);
    });
  }, []);

  useEffect(() => {
    if (!isModalOpen) {
      addForm.resetFields();
    }
  }, [isModalOpen]);
  useEffect(() => {
    if (!isSensorModalOpen) {
      sensorForm.resetFields();
    }
  }, [isSensorModalOpen]);

  const closeModal = () => {
    setIsModalOpen(false);
  };
  const addConfigHandle = () => {
    setBtnLoading(true);
    addForm.validateFields().then(() => {
      let data = addForm.getFieldsValue();
      addRuleConfigAPI(data).then(res => {
        if (res) {
          message.success('新增成功');
          setIsModalOpen(false);
          getConfigList();
        }
        setBtnLoading(false);
      });
    });
  };
  // Usage of DebounceSelect

  interface DeviceCodeValue {
    label: string;
    value: string;
  }
  const [deviceCodeValue, setDeviceCodeValue] = useState<DeviceCodeValue[]>([]);
  async function getDeviceCodeList(
    collectionDeviceCode: string
  ): Promise<DeviceCodeValue[]> {
    return getUnbindDeviceAPI({ collectionDeviceCode }).then(res => {
      return res.data.map(item => {
        return {
          label: item,
          value: item,
        };
      });
    });
  }
  const bindSensorHandle = () => {
    sensorForm.validateFields().then(
      () => {
        setBtnLoading(true);
        let collectionDeviceCodes = [
          ...sensorForm.getFieldValue('collectionDeviceCodes'),
          ...sensor,
        ];
        bindSensorAPI({
          deviceCode: currentDeviceType,
          collectionDeviceCodes,
        })
          .then(res => {
            if (res) {
              message.success('绑定成功');
              setIsSensorModalOpen(false);
              getConfigList();
            }
            setBtnLoading(false);
          })
          .catch(err => {
            console.log(err);
            setBtnLoading(false);
          });
      },
      () => {}
    );
  };
  const unBindSensorHandle = (collectionDeviceCode: string) => {
    modal.warning({
      title: '解绑',
      content: `确定解绑“${collectionDeviceCode}”传感器吗 `,
      okButtonProps: { loading: btnLoading },
      okText: '解绑',
      onOk() {
        setBtnLoading(true);
        unBindSensorAPI({
          collectionDeviceCode,
          deviceCode: currentDeviceType,
        })
          .then(res => {
            message.success('解绑成功');
            setSensor(res.data);
            getConfigList();
          })
          .catch(err => {
            setBtnLoading(false);
            console.log(err);
          })
          .finally(() => {
            setBtnLoading(false);
          });
      },
    });
  };

  //切换page
  const onPageChange = (pagination: any) => {
    setPagination({ ...pagination, page: pagination.current });
  };
  useEffect(() => {
    getConfigList();
  }, [pagination.page, pagination.pageSize]);
  //重置
  const resetFilterFrom = () => {
    filterForm.resetFields();
    getConfigList();
  };
  const checkCode = (_: any, value: string) => {
    const reg = /^(?=.*\d)(?=.*[A-Z])[0-9A-Z]+$/;
    console.log(reg.test(value), 1111);
    if (value.trim()) {
      if (!reg.test(value)) {
        return Promise.reject(
          new Error('仅支持输入数字和大写字母且至少包含一位数字和一位大写字母')
        );
      }
      if (value.length > 12 || value.length < 12) {
        return Promise.reject(new Error('传感器编码必须为12位'));
      }
      return Promise.resolve();
    }
    return Promise.reject(new Error('请输入传感器编号'));
  };

  const search = () => {
    setPagination({ ...pagination, page: 1 });
    getConfigList();
  };

  return (
    <div className={classNames(style['analysis-config-wrap'], 'flex-column')}>
      {/* <div className={style.tips}>
        <Icon name="icon-info" style={{ color: '#4E6FF5', fontSize: 18 }} />
        <p className={style['tips-desc']}>
          统计分析规则均为系统预置，默认每台设备关联一条计算规则，若用户希望新增分析内容或修改利用率计算方法，请联系技术支持人员。
        </p>
      </div> */}
      {/* search from */}
      <div className={style.formDiv}>
        <Form
          name="filterForm"
          form={filterForm}
          layout="inline"
          autoComplete="off"
          onChange={() => setPagination({ ...pagination, page: 1 })}>
          <Form.Item label="" name="searchKey">
            <Input
              prefix={<Icon name="icon-search" className={style.iconStyle} />}
              placeholder="请输入关键字进行查询"
              style={{ width: 240 }}
              allowClear
            />
          </Form.Item>
          <Form.Item label="" name="deviceTypes" className={style.selectDiv}>
            <BeforefixSelect
              options={deviceTypeOptions}
              beforefix="设备类型"
              placeholder="请选择设备类型"
              allowClear
              style={{ width: 150 }}
            />
          </Form.Item>
        </Form>
        <div>
          <Button
            htmlType="button"
            style={{ marginRight: '8px' }}
            onClick={resetFilterFrom}>
            重置
          </Button>
          <Button type="primary" htmlType="submit" onClick={search}>
            查询
          </Button>
        </div>
      </div>
      <Table
        columns={columns}
        loading={tableLoading}
        expandable={{
          expandIcon: () => null,
        }}
        scroll={{
          y: 'calc(100vh - 410px)',
        }}
        onChange={onPageChange}
        pagination={
          pagination.total > 10
            ? {
                current: pagination.page,
                pageSize: pagination.pageSize,
                total: pagination.total,
                showTotal: total => `共${total}条`,
                showSizeChanger: true,
                showQuickJumper: true,
              }
            : false
        }
        dataSource={dataSource}
      />
      {/* 新增modal */}
      <DefaultModal
        forceRender
        title="新增配置"
        getContainer={false}
        open={isModalOpen}
        onOk={addConfigHandle}
        onCancel={closeModal}>
        <Form
          name="addForm"
          form={addForm}
          initialValues={{
            monitorMethod: '智能插座',
          }}
          // onFinish={onFinish}
          // onFinishFailed={onFinishFailed}
          layout="vertical"
          autoComplete="off">
          <Form.Item
            label="配置名称"
            name="configName"
            rules={[{ required: true, message: '请输入配置名称' }]}>
            <Input placeholder="请输入配置名称" />
          </Form.Item>

          <Form.Item
            label="设备编号"
            name="deviceCode"
            rules={[{ required: true, message: '请选择设备编号' }]}>
            <SelectDebounce
              value={deviceCodeValue}
              placeholder="请输入并选择设备编号"
              fetchOptions={getDeviceCodeList}
              onChange={newValue => {
                setDeviceCodeValue(newValue as DeviceCodeValue[]);
              }}
              style={{ width: '100%' }}
            />
          </Form.Item>
          <Form.Item label="监控方式" name="monitorMethod">
            <Select
              placeholder="请选择监控方式"
              options={[{ label: '智能插座	', value: '智能插座	' }]}></Select>
          </Form.Item>
          <Form.Item label="规则描述" name="configRemark">
            <TextArea rows={2} placeholder="请输入规则描述" />
          </Form.Item>
        </Form>
      </DefaultModal>
      {/* 传感器modal */}
      <DefaultModal
        forceRender
        centered
        title="传感器管理"
        getContainer={false}
        open={isSensorModalOpen}
        footer={
          <>
            <Button onClick={() => setIsSensorModalOpen(false)}>取消</Button>
            {sensor.length === 0 && (
              <Button
                type="primary"
                onClick={bindSensorHandle}
                loading={btnLoading}>
                保存
              </Button>
            )}
          </>
        }
        onCancel={() => setIsSensorModalOpen(false)}>
        <div
          className={classNames(style['bind-sensor'])}
          style={{
            marginBottom: sensor.length === 0 ? 16 : 0,
          }}>
          <p className={style.bindLabel}>已绑定传感器：</p>
          <div className={style['sensor-list']}>
            {sensor.length === 0 ? (
              <span style={{ lineHeight: '32px' }}>暂无绑定数据</span>
            ) : (
              sensor.map(item => {
                return (
                  <div
                    className={classNames(style['sensor-item'], 'flex-s-b')}
                    key={item}>
                    <span>{item}</span>
                    <a
                      style={{ marginLeft: '8px', color: '#4E6FF5' }}
                      onClick={() => unBindSensorHandle(item)}>
                      解绑
                    </a>
                  </div>
                );
              })
            )}
            {contextHolder}
          </div>
        </div>
        {sensor?.length === 0 && (
          <Form
            name="sensorForm"
            form={sensorForm}
            initialValues={{}}
            {...formItemLayoutWithOutLabel}
            // colon={false}
            autoComplete="off">
            <Form.List name="collectionDeviceCodes" initialValue={['']}>
              {(fields, { remove }) => (
                <>
                  {fields.map((field, index) => (
                    <Form.Item
                      {...(index === 0
                        ? formItemLayout
                        : formItemLayoutWithOutLabel)}
                      label={index === 0 ? '传感器编号' : ''}
                      required={true}
                      key={field.key}>
                      <Form.Item
                        {...field}
                        validateTrigger={['onChange', 'onBlur']}
                        rules={[
                          {
                            required: true,
                            whitespace: true,
                            validator: checkCode,
                            validateTrigger: ['onBlur'],
                          },
                        ]}
                        noStyle>
                        <Input
                          placeholder="请输入传感器编号"
                          style={{ width: '85%' }}
                          maxLength={12}
                          minLength={12}
                        />
                      </Form.Item>
                      {fields.length > 1 ? (
                        <MinusCircleOutlined
                          className={style['dynamic-delete-button']}
                          onClick={() => remove(field.name)}
                        />
                      ) : null}
                    </Form.Item>
                  ))}
                  {/* 支持绑定多个传感器*/}
                  {/* <Button
                  type="dashed"
                  onClick={() => add()}
                  style={{
                    width: '100%',
                    color: '#4E6FF5',
                    borderColor: '#4E6FF5',
                    fontSize: 14,
                  }}
                  size="large"
                  icon={<PlusOutlined />}>
                  添加传感器
                </Button> */}
                </>
              )}
            </Form.List>
          </Form>
        )}
      </DefaultModal>
    </div>
  );
};

export default AnalysisConfig;
